<template>
  <div class="flex flex-wrap px-17px">
    <div
      v-for="(list, index) in listStore.data"
      :key="list.name + Math.random().toString(16).slice(2, 8)"
      :class="{ 'mr-24px': (index + 1) % 4 !== 0, 'mt-24px': index >= 0 }"
    >
      <product-list
        :id="list.id"
        :title="list.name"
        :img="list.imgs[0]?.url || ''"
        :score="list.score"
        :price="list.price"
        :video="list.video"
        :discount-price="list.discountPrice"
        :labels="list.sell_point"
        :sales="list.sales"
        :is-combo="listStore.isCombo"
        @on-select="addProduct(list)"
      ></product-list>
    </div>
  </div>
  <category v-if="showCategory" :is-combo="listStore.isCombo" @on-close="closeCategory" />
  <cart-col @open-cart="openCart" />
  <cart-item v-model:show="showOpenCart" />
</template>

<script setup lang="ts">
import useHttp from '@renderer/utils/http'
import { onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'
import { useListStore } from '@renderer/store/modules/list'
import ProductList from '@renderer/components/list/index.vue'
import { useCategoryStore } from '@renderer/store/modules/category'
import Category from '@renderer/components/category/index.vue'
import CartCol from '@renderer/views/mall/recommend/components/cart-col.vue'
import CartItem from '@renderer/views/mall/recommend/components/cart-item.vue'
const categoryStore = useCategoryStore()
const listStore = useListStore()
const showCategory = ref<boolean>(false)
const showOpenCart = ref<boolean>(false)

const route = useRoute()

onMounted(async () => {
  const { data: res } = await useHttp(`/coupon/c/spus?id=${route.query.id}`).get().json()
  if (res.value.code === 200) {
    listStore.setList(
      res.value.data.map((spu: any) => {
        if (spu.imgs) {
          spu.imgs = JSON.parse(spu.imgs)
        }
        if (spu.default_sku) {
          spu.default_sku = JSON.parse(spu.default_sku)
          spu.price = spu.default_sku?.price
        }
        if (spu.sell_point) {
          spu.sell_point = spu.sell_point.split('\n')
        }
        return spu
      })
    )
  }
})
const addProduct = async (list) => {
  if (listStore.isCombo) {
    const { data: res } = await useHttp(`/combo/c/detail?id=${list.id}`).get().json()
    if (res.value.code === 200) {
      const { spus } = res.value.data
      categoryStore.setComboSpu(spus)
      categoryStore.setCombo(res.value.data)
      categoryStore.setComboSkus(
        spus.map((spu) => {
          return spu.skus.map((sku) => ({
            ...sku,
            discount: spu.discount
          }))
        })
      )
    }
  } else {
    await categoryStore.setSkus(list.id, list)
    categoryStore.setSpu(list)
  }
  showCategory.value = true
}

const closeCategory = () => (showCategory.value = false)

const openCart = () => {
  showOpenCart.value = !showOpenCart.value
}
</script>

<style scoped></style>
